/*
 * Copyright (c) 2010, Nikolaus Moll
 * All rights reserved.
 */
package net.miblounge.gradecalculator.srdxeditor.dialogs;

import net.miblounge.gradecalculator.core.descriptors.modulelistitems.IndividualModule;
import net.miblounge.gradecalculator.guicommon.dialogs.AbstractDialog;
import net.miblounge.gradecalculator.guicommon.layouts.VerySimpleLayout;
import net.miblounge.gradecalculator.guicommon.util.StringUtil;
import net.miblounge.miglayout.qt.MigLayout;

import com.trolltech.qt.gui.QGroupBox;
import com.trolltech.qt.gui.QLabel;
import com.trolltech.qt.gui.QLineEdit;
import com.trolltech.qt.gui.QWidget;

public class IndividualModuleDialog extends AbstractDialog {
	
	private QLineEdit leName;
	private QLineEdit leECTS;

	private final IndividualModule module;
	
	public IndividualModuleDialog(final QWidget parent, final IndividualModule module)
	{
		super(parent);
		setWindowTitle(tr("Individual Module"));
		
		this.module = module;
		
		setClientArea(createClientArea());
		
		leName.setFocus();
		leName.setSelection(0, leName.text().length());
		
		revalidate();
	}
	
	private QWidget createClientArea()
	{
		final QGroupBox result = new QGroupBox(tr("Individual Module"), this);
		final VerySimpleLayout layout = new VerySimpleLayout(result);
		result.setLayout(layout);

		final QWidget container = new QWidget(result);
		layout.setWidget(container);
		final MigLayout layoutContainer = new MigLayout("", "[][grow,fill]15[grow]"); 
		container.setLayout(layoutContainer);
		
		layoutContainer.addWidget(new QLabel(tr("Name:")));
		leName = new QLineEdit(module.getName(), this);
		leName.textEdited.connect(this, "revalidate()");
		layoutContainer.addWidget(leName, "span, growx");

		layoutContainer.addWidget(new QLabel(tr("ECTS:")));
		leECTS = new QLineEdit(String.valueOf(module.getECTS()), this);
		leECTS.textEdited.connect(this, "revalidate()");
		layoutContainer.addWidget(leECTS);
		
		return result;
	}
	
	
	protected boolean validate()
	{
		if (StringUtil.cleanString(leName.text()).equals("")) {
			return false;
		}
		
		try {
			final float ects = Float.parseFloat(leECTS.text().replace(',', '.'));
			if (ects <= 0) {
				return false;
			}
		} catch (final NumberFormatException e) {
			return false;
		}
	
		return super.validate();
	}

	@Override
	public void apply()
	{
		super.apply();
		module.setName(StringUtil.cleanString(leName.text()));
		module.setECTS(Float.parseFloat(leECTS.text().replace(',', '.')));
		//module.setHoursPerWeek(Integer.parseInt(leHoursPerWeek.text()));
	}


}
